import { Component, OnInit, Input } from "@angular/core";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { Router } from "@angular/router";

import { JPush } from "@jiguang-ionic/jpush/ngx";

import * as CryptoJS from 'crypto-js';

import { EventService } from "src/app/shared/service/event.service";

import { CustomValidators } from "../../shared/custom-validators/custom-validators";
import { AppGlobalService } from "../../shared/service/app-global.service";
import { HttpService } from "../../shared/service/http.service";
import { ChatService } from "../../shared/service/chatService";
import { IndexedDBService } from "../../shared/service/indexed-db.service";
import { MapBaiduService } from '../../shared/service/map.baiduapi';
import { MessageService } from "../../shared/service/message.service";
import { ShareService } from "../../shared/service/share.service";
import { ViewChild } from '@angular/core';
import { ModalController, Platform } from '@ionic/angular';
import { PageModalService } from "src/app/shared/service/page-modal-service";
import { ProcessLoginDataService } from "src/app/shared/service/process-login-data.service";
declare const Umeng;
@Component({
  selector: "app-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.scss"]
})
//tslint:disable
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  open: boolean;
  accountNum = '';
  passwordNum = '';
  messages: any;
  appTypeCustom: any;
  disableBtn = false;
  isCheckRead = false;
  isNeedGetBadgeAfterSubmit = false;
  useToTargetFirst = false; // 蜂喔用户 2022-06-08 新增表示优先使用toTarget
  currentBackTarget = '';

  @ViewChild('accountInput') accountInput;
  @ViewChild('passwordInput') passwordInput;

  @Input() tagData: any = {};
  constructor(
    private platform: Platform,
    private eventService: EventService,
    private modalCtrl: ModalController,
    private fb: FormBuilder,
    private http: HttpService,
    private shareService: ShareService,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private indexedDBService: IndexedDBService,
    private mapBaiduService: MapBaiduService,
    private message: MessageService,
    private webSocketTalk: ChatService,
    private plService: ProcessLoginDataService,
    private jPush: JPush,
    public router: Router
  ) {
  }
  ngOnInit() {

    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    const that = this;
    console.log("msg----->entrance login" + new Date().toLocaleDateString());
    let mobile =
      localStorage.getItem("loginAccount") &&
        localStorage.getItem("loginAccount") !== "undefined"
        ? localStorage.getItem("loginAccount")
        : "";
    if (mobile && mobile.length > 11) {
      mobile = '';
    }
    // const parttern = "[A-Za-z0-9]{6,12}";
    this.loginForm = this.fb.group({
      account: [mobile, [Validators.required, CustomValidators.phone]],
      password: [
        "",
        [
          Validators.required,
          Validators.minLength(6),
          Validators.maxLength(30)
        ]
      ]
    });
    this.accountNum = mobile;
    // api新增需求 
    if (this.tagData.badge !== undefined) {
      this.isNeedGetBadgeAfterSubmit = true;
    }
    if (localStorage.getItem('client') !== 'APP') {
      this.tagData.wxLink = null;// 2.1.0 蜂喔用户授权登录;
    }
    if (this.tagData.button.actionElement && this.tagData.button.actionElement.param && this.tagData.button.actionElement.param.length > 0) {
      const paramArray = this.tagData.button.actionElement.param;
      for (let i = 0; i < paramArray.length; i++) {
        const tempItem = paramArray[i];
        if (tempItem.name === 'back_target') {
          this.currentBackTarget = tempItem.value;
          localStorage.setItem('back_target', tempItem.value);

        }
        if (tempItem.name === 'useToTarget') {
          this.useToTargetFirst = true;
        }
      }

    }
  }
  register() {
    const register = this.tagData.register;
    const params = {
      pageId: register.link.target,
      params: {},
      sessionId: localStorage.getItem("sessionId")
    };
    this.appGlobalService.goToForward(params);
  }

  changePwd() {
    const forget = this.tagData.forget;
    const params = {
      pageId: forget.link.target,
      params: {},
      sessionId: localStorage.getItem("sessionId")
    };
    localStorage.setItem("loginAccount", this.loginForm.value.account);
    this.appGlobalService.goToForward(params);
  }

  getErrors() {
    if (this.loginForm.controls.account.errors) {
      if (this.loginForm.controls.account.errors.required) {
        this.appGlobalService.showToast("请输入手机号码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的手机号码", 3000, "top");
      }
    } else if (this.loginForm.controls.password.errors) {
      if (this.loginForm.controls.password.errors.required) {
        this.appGlobalService.showToast("请输入密码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的密码", 3000, "top");
      }
    }
  }

  submitForm(): void {
    if (this.isCheckRead === false) {
      this.appGlobalService.showToast('请先同意用户协议及隐私政策再继续使用APP', 2000, 'top');
      return;
    }
    if (this.loginForm.status === "INVALID") {
      this.getErrors();
      return;
    }
    this.disableBtn = true;
    this.loginForm.value.device_model = this.getDeviceModel();
    const obj = {
      account: this.loginForm.value.account,
      password: this.appGlobalService.encryptDes(this.loginForm.value.password),
      // isPreView: this.appGlobalService.isPreView,
      device_model: this.getDeviceModel()
    };    
    // 2024.09.19 huawei
    if(localStorage.getItem('huawei')){
      Object.assign(obj, { amobile:'huawei' });
    }
    // 2023.11.24 getUuid
    Object.assign(obj, { imei: this.eventService.getUuid(), clientType: this.appGlobalService.clientType });
    if (localStorage.getItem("isDetailPage")) {
      obj['skip'] = 0;
    }
    const params = {
      content: obj,
      id: this.tagData.button.id,
      sessionId: localStorage.getItem("sessionId")
    };
    if (
      this.tagData.button.actionElement &&
      this.tagData.button.actionElement.param
    ) {
      this.tagData.button.actionElement.param.map(item => {
        params.content[item.name] = item.value;
      });
    }
    const that = this;
    this.http.post("application/submit", params, res => {
      if (res.success) {
        if (params.content.password && params.content.password.length > 0 ) {
          const alp = this.appGlobalService.encryptALP(params.content.password);
          localStorage.setItem('ALP', alp);
         }
        this.eventService.eventEmit.removeAllListeners("clearlistTagRefreshTime");
        if (res.data.position) {
          this.setPxwCityPosition(res.data.position);
        }
        // 2024.07.09 初始化临时全局变量
        that.appGlobalService.initTemporaryVariables();
        if (res.data.user_id) {

          localStorage.setItem("userId", res.data.user_id);
          localStorage.setItem("loginAccount", this.loginForm.value.account);
          this.appGlobalService.initUmengEventWithParameters("enter_app_with_loginAccount_event");
          that.jPush
            .setAlias({
              sequence: 1,
              alias: this.appGlobalService.pushAlias + params.content.account
            })
            .then(
              result => {
                const sequence = result.sequence;
                const alias = result.alias;
                console.log("设置别名成功：" + alias);
              },
              error => {
                const sequence = error.sequence;
                const errorCode = error.code;
                console.log("设置别名失败：" + errorCode);
              }
            );

          this.http.get(
            "message/userinfo/im/" + res.data.user_id,
            response => {
              const data = response.data;
              if (res.data.user_id.includes('random')) {
                data.nickname = '访客';
              }
              if (data.nickname) {
                this.appGlobalService.currentNickName = data.nickname;
                localStorage.setItem('currentNickName', data.nickname);
              }
              if (data.avatar_url === null) { // 没头像给默认头像
                data.avatar_url = this.appGlobalService.defaultImg;
              }
              if (data.avatar_url) {
                this.appGlobalService.getBase64Str(data.avatar_url + "?x-oss-process=image/resize,h_36", str => {
                  localStorage.setItem('currentAvatarStr', str);
                  that.webSocketTalk.setAvatar(res.data.user_id, str);
                });
                this.appGlobalService.currentAvatarUrl = data.avatar_url;
                localStorage.setItem('currentAvatarUrl', data.avatar_url);
              }
              localStorage.setItem('currentWorkMobile', data.work_mobile);
              // 2024.08.02 联调接口返回参数
              if (res.data.shopGoodsCartCount) {
                // tslint:disable-next-line:no-string-literal
                data['shopGoodsCartCount'] = res.data.shopGoodsCartCount;
              }
              that.webSocketTalk.currentUserObj = data;
              this.indexedDBService.putByKeyCallbak(data, res.data.user_id, "user", () => {
                if (res.data.shopGoodsCartCount) {
                  that.webSocketTalk.setCartItemCount(res.data.shopGoodsCartCount);
                }
              });
            },
            error => {
              console.log("msg-----> error:" + JSON.stringify(error));
            }
          );
          // this.im.connectting(res.data.user_id);
          // 检测timer则需重新启动定时器
          // this.im.onStartMsgTimer();
          // this.connectting(res.data.user_id);
          // 检查 邀约消息列表和 消息详情表数据是否有变化
          // this.im.checkAndLoadChatData();


          // websocket链接
          this.webSocketTalk.connectting(this.loginForm.value.account, true, (eData) => {
            console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  ws.connectting   ', eData);
          });
          if (this.appGlobalService.clientType === 'pxw') {
            localStorage.setItem('startRefreshTimerTag', '1');
            this.eventService.eventEmit.emit("startRefreshTimer");
          }
        }

        // 登录成功后发现 alert 2s后跳转
        if (res.data.alert) {

          setTimeout(() => {
            const link = {
              params: res.data.alert.params,
              target: res.data.alert.target,
              type: 'pageModal'
            }
            this.pageModalService.openPage(link);
          }, 2000);
        }
        localStorage.setItem("loginStatus", "true");
        this.appGlobalService.loginStatus = true;

        if (!this.appGlobalService.disableRefreshAfterLogin && this.appGlobalService.disableRefreshAfterLogin === '') {
          localStorage.setItem("needRefreshTab1", "true");
          localStorage.setItem("needRefreshTab2", "true");
          localStorage.setItem("needRefreshTab3", "true");
          localStorage.setItem("needRefreshTab4", "true");
          localStorage.setItem("needRefreshTab5", "true");
        } else {
          this.appGlobalService.disableRefreshAfterLogin = '';
        }

        if (that.isNeedGetBadgeAfterSubmit) {
          const tempParams = {
            id: this.tagData.badge,
            sessionId: localStorage.getItem("sessionId")
          }
          this.http.post("application/submit", tempParams, res => {
            if (res.success) {
              that.updateBadge(res.data.badge);
            }
          });
        } else {
          if (res.data && res.data.badge) {
            that.updateBadge(res.data.badge);
          }
        }



        // 1.9.17 登录成功之后新增跳转
        if (this.tagData.successLink !== undefined) {

          // 1.9.18 优先使用back_target
          if (this.useToTargetFirst && this.tagData.totarget) {
            this.tagData.successLink.target = this.tagData.totarget;
            const targetObj = JSON.parse(localStorage.getItem('targetObj'));
            // 1.9.18 解决未登录跳转到我的订单
            if (targetObj !== null) {
              if (targetObj.forward && targetObj.forward.params) {
                Object.assign(this.tagData.successLink.params, targetObj.forward.params);
                if (targetObj.forward.params.modalCss !== undefined) {
                  this.tagData.successLink.type = 'modal';
                }
              }
            }
          }
          if (this.tagData.successLink.type === 'modal') {
            this.appGlobalService.popTarget();
            this.appGlobalService.goBack();

            setTimeout(() => {
              this.pageModalService.openPage(this.tagData.successLink);
            }, 500);
          } else {
            setTimeout(() => {
              this.pageModalService.openPage(this.tagData.successLink);
            }, 1500);
          }
        } else {
          if (localStorage.getItem("useTarget") === "true") {
            const cityId = JSON.parse(localStorage.getItem("position"))
              ? JSON.parse(localStorage.getItem("position")).code
              : 4403;
            const pageParams = {
              pageId: res.target,
              params: {
                code: cityId
              },
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
            localStorage.removeItem("useTarget");
          } else {
            const skip = res.skip;
            if (skip && skip === 1) {
              // "是否跳转页面 0不跳/1跳"
              const pageParams = {
                pageId: res.target,
                params: res.params,
                sessionId: localStorage.getItem("sessionId")
              };
              this.appGlobalService.goToForward(pageParams);
            } else if (localStorage.getItem("isDetailPage") && skip === 0) {
              this.appGlobalService.popTarget();
              this.appGlobalService.goBack();
            } else if (skip === 0) {


              let tmpParams = res.params;
              if (localStorage.getItem('back_target') !== null) {
                tmpParams = params.content;
              }
              if (res.back_target !== undefined) {
                res.target = parseInt(res.back_target);
              }
              const pageParams = {
                pageId: res.target,
                params: tmpParams,
                sessionId: localStorage.getItem("sessionId")
              };
              this.appGlobalService.goToForward(pageParams);
            } else if (skip && skip === 4) { // 跳转到模态窗口
              // "是否跳转页面 0不跳/1跳"
              const link = {
                pageId: res.target,
                params: res.params,
                sessionId: localStorage.getItem("sessionId")
                , type: 'modal'
              };
              this.pageModalService.openPage(link);
            } else {
              localStorage.setItem("needRefresh", "true");
              this.appGlobalService.goBack();
            }
          }
        }

      } else {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }
      this.disableBtn = false;
    });
  }
  editStyle() {
  }
  checkTime(i) {
    if (Number(i) < 10) {
      i = "0" + i;
    }
    return i;
  }
  async isYestday(theDate) {
    return (await new Date().getDate()) - theDate.getDate() === 1;
  }
  isSameWeek(old, now) {
    const oneDayTime = 1000 * 60 * 60 * 24;
    const oldCount = parseInt(old.getTime() / oneDayTime + "");
    const nowOther = parseInt(now.getTime() / oneDayTime + "");
    return (
      parseInt((oldCount + 4) / 7 + "") === parseInt((nowOther + 4) / 7 + "")
    );
  }
  getTime() {
    const m = parseInt(new Date().getMinutes() + "");
    return parseInt(new Date().getHours() + "") + ":" + (m < 10 ? "0" + m : m);
  }
  getDeviceModel() {
    return localStorage.getItem("device");
  }




  // 处理 员工 当前定位城市
  setPxwCityPosition(positionInfo) {
    if (this.appGlobalService.clientType === 'pxw') {
      // 如果有第一次城市信息，firstPostion === {}，存firstPostion
      const firstPostion = localStorage.getItem('firstPostion');
      if (!firstPostion) {
        localStorage.setItem('firstPostion', JSON.stringify(positionInfo));
        localStorage.setItem('position', JSON.stringify(positionInfo));
        // 通过城市名称设置经纬度
        this.mapBaiduService.getPointByName(positionInfo.name, (point) => {
          positionInfo.center = { lng: point.lng, lat: point.lat };
          localStorage.setItem('position', JSON.stringify(positionInfo));
        });
      }
    }
  }



  focusInput(type) {
    if (type === '1') {
      this.accountInput.setFocus();
    } else if (type === '2') {
      this.passwordInput.setFocus();
    }
  }
  async openArgument() {
    this.appGlobalService.openUrl("服务协议", this.appGlobalService.serviceAgreementLink);
  }
  async alertPrivacyPolicy() {
    this.appGlobalService.openUrl("隐私权限", this.appGlobalService.privatePolicyLink);
  }
  checkRead() {
    this.isCheckRead = !this.isCheckRead;
  }

  updateBadge(badge) {
    if (badge && badge.length > 0) {
      badge.forEach(element => {
        const key = Object.keys(element)[0];
        if (Number(element[key]) >= 0) {
          console.log("msg----->" + Number(element[key]));
          this.eventService.eventEmit.emit("firstBadgeForTab", {
            [key]: Number(element[key])
          });
        }
      });
    }
  }


  wxAuth() {
    // 2024.03.27 微信登录也要勾选隐私协议
    if (this.isCheckRead === false) {
      this.appGlobalService.showToast('请先同意用户协议及隐私政策再继续使用APP', 2000, 'top');
      return;
    }
    this.pageModalService.wxAuth(this.tagData);
  }
}


